<template>
  <view>
      <van-popup :show="visible" round :position="position" :z-index="zIndex" :closeable="closeable" @click-overlay="visible = false" @close="closePopup">        
        <van-cell-group :border="false">
          <van-cell title="阅读有奖 | 申请使用" label="请填写个人信息，以便在应用中显示和使用" />
          <van-cell title="头像" is-link>
            <button class="btn-avatar" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
              <van-image  round width="60rpx" height="60rpx" class="img-aavatar" :src="form.headimgurl"/>
            </button> 
          </van-cell>
          <van-field label="昵称" placeholder="请输入昵称" input-align="right"  type="nickname" :value="form.nickname" @blur="getNickname" @input="e => form.nickname = e.detail" is-link />
        </van-cell-group>
        <view class="p-a-15">
          <van-button class="btn-red" round block :loading="btnLoading" @click="submitForm">确定</van-button>
        </view>
      </van-popup>
  </view>
</template>
<script>
import upload from '@/static/mixins/upload';
export default {
  mixins: [upload],
  props:{
      title: {
          type: String,
      },
      position: {
        type: String,
        default: () => 'bottom'
      },
      zIndex: {
        type: Number,
        default: () => 100,
      },
      closeable: {
        type: Boolean,
        default: () => true,
      }
  },
  data(){
      return{
          visible: false,
          btnLoading: false,
          form:{
            uid: null,
            headimgurl: null,
            nickname: null,
          }
      }
  },
  methods:{
    init(){
      let userInfo = this.$store.state.user_info;
      this.form.uid = userInfo.id;
      this.visible = true;         
    },
    onChooseAvatar(e) {
      let url = e.detail.avatarUrl;      
      this.handleUpload(url);
    },
    uploadSuccess(data){
      this.form.headimgurl = data.path;
    },
    getNickname(e){
      this.form.nickname = e.detail.value;
    },
    verifyForm(){
      if(!this.$verify.null(this.form.headimgurl, '请选择头像')){
        return false;
      }
      if(!this.$verify.null(this.form.nickname, '请填写昵称')){
        return false;
      }
      return true;
    },
    submitForm(){
      if(!this.verifyForm()){
        return;
      }
      this.btnLoading = true;
      this.$store.dispatch('updateUserInfo', this.form).then(res => {
        this.$emit('confirm',res);
        this.btnLoading = false;
        this.visible = false;
      },msg => {
        this.btnLoading = false;
      });
    },
    closePopup(){
      this.visible = false;
      this.btnLoading = false;
      this.$emit('close');
    }
  }
}
</script>
<style lang="scss" scoped>
.img-avatar{margin-right:0;}
.btn-avatar{
  border:none;background:none;padding:0;margin:0;display:inline-block;height:64rpx;
  &:after{display:none;}
}
</style>